package ntd.util.frame.javacv.ai_fuming;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.db.Db;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.log.StaticLog;
import cn.hutool.setting.dialect.Props;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.AiModelBean;
import org.apache.commons.net.ftp.FTPFile;

import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

/*
    Ai视频分析结果下载：
    1、根据文件名称、模型对应预警图片
    2、删除原始视频，下载视频文件结果
    3、记录到预警图片对应的数据库
 */
public class AIVideoDownload {
    public static void main(String[] args) {

        AiModelBean modelBean = new AiModelBean();


        for (AiModelBean bean : modelBean.getModelList()) {

            //定时任务，每隔30分钟执行一次
            CronUtil.schedule("0 0/1 * * * ?", (Runnable) () -> {
                //获取配置文件
                Props prop = new Props("ai-config.properties");
                // 数据库操作
                Db use = Db.use(FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c"));


                //下载到本地的目录
                String basePath = prop.getStr("ai-local-file-path");//文件访问地址;

                //当前日期
                String currentDate = LocalDateTimeUtil.format(LocalDateTime.now(), "yyyyMMdd");

                String downloadPath = basePath + "video/" + bean.getType() + "/" + currentDate;//本地文件的输出
                if (!FileUtil.exist(downloadPath)) {
                    FileUtil.mkdir(downloadPath);
                }
                //服务器结果目录
                StringBuilder serverResultPath = new StringBuilder(prop.getStr("ai-server-result-base-path"));
                //连接ftp
                Ftp ftp = new Ftp(bean.getFtpIp(), prop.getInt("ai-ftp-port"), prop.getStr("ai-ftp-username"), prop.getStr("ai-ftp-password"));
                //各个模型对应的视频目录
                serverResultPath.append(bean.getVideoResultPath());

                //遍历此模型文件夹下所有的日期目录
                if (ftp.exist(serverResultPath.toString())) {
                    List<FTPFile> datePaths = ftp.lsFiles(serverResultPath.toString(), FTPFile::isDirectory);
                    //查找模型下的日期目录
                    if (datePaths != null && datePaths.size() > 0) {
                        for (FTPFile datePath : datePaths) {//日期目录
                            String serverDatePath = serverResultPath + "/" + datePath.getName();

                            List<FTPFile> videos = ftp.lsFiles(serverDatePath, FTPFile::isFile);
                            //查找目录下的视频文件
                            if (videos != null && videos.size() > 0) {
                                StaticLog.info("开始下载视频文件==");
                                for (FTPFile video : videos) {//下载视频文件
                                    ftp.download(serverDatePath + "/" + video.getName(), FileUtil.file(downloadPath));

                                    String jsonPath = serverDatePath.replace("video", "json") + "/" + video.getName().replace(".mp4", ".json");

                                    //下载json文件
                                    if (ftp.exist(jsonPath)) {
                                        StaticLog.info(jsonPath);
                                        ftp.download(jsonPath, FileUtil.file(downloadPath));
                                    }
                                    StaticLog.info("视频文件名称==" + video.getName());


                                    try {
                                        //写入数据库
                                        String imageName = video.getName().replace(bean.getType() + "-video.mp4", "image.jpg");
                                        String videoPath = StrUtil.replace(downloadPath + "/" + video.getName(), basePath, "");
//                                    StaticLog.info("视频文件名称=="+videoPath+"==="+downloadPath+"/"+video.getName().replace(".mp4",".json")+"=="+imageName);
                                        for (String alertType:bean.getObjectType()){
                                            use.execute("update airesult set videoUrl = ?,videoJsonUrl=? where imageName = ? AND alert_type=?",
                                                    videoPath, downloadPath + "/" + video.getName().replace(".mp4", ".json"), imageName, alertType);

                                        }

                                    } catch (SQLException e) {
                                        StaticLog.error(e, "[AI][视频下载][{}]失败...");
                                    }


                                    //下载完毕删除文件


                                    ftp.delFile(serverDatePath + "/" + video.getName());
                                    ftp.delFile(jsonPath);
                                }
                            } else {
                                //无文件，删除目录
                                ftp.delDir(serverDatePath);
                            }
                        }
                    }
                }


                try {
                    ftp.close();

                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            });

        }

        CronUtil.start();
    }
}
